<template>
  <div>
    <div class="flex justify-between">
      <div
        style="flex: 1 0 600px"
      >
        <!-- title -->
        <PageTitle>
          {{ $t("menu.M_12688010") }}
          <template #rightButtons>
            <el-button
              v-permission="{
                permission: '12688010.ROLE_MANAGE',
              }"
              v-if="loginUser.topOrgFlag === 1"
              type="primary"
              class="w-8 mr-4"
              @click="handleAdd"
            >
              <svg-icon icon-class="plus" class="text-lg" />
            </el-button>
          </template>
        </PageTitle>
        <!-- <div class="box-header flex items-center justify-between">
            <h1>
              <i class="el-icon-user title-logo" />
              {{ $t('menu.M_12688010') }}
            </h1>
            <el-button v-permission="{
              permission: '12688010.ROLE_MANAGE'
            }" v-if="loginUser.topOrgFlag === 1" type="primary"  class="p-1.5 align-middle"  size="small" @click="handleAdd">
              <svg-icon icon-class="plus" class="text-lg" />
            </el-button>
          </div>
          <hr class="mb-3"> -->
        <el-scrollbar style="height: calc(100vh - 140px)" wrap-style="overflow-x:hidden;">
          <div style="padding: 20px">
            <el-row v-loading="listLoading" :gutter="24">
              <el-col
                v-for="role in roleList"
                :lg="6"
                :md="12"
                :sm="24"
                :key="role.roleId"
                :data-id="role.roleId"
                class="draggable-container auto-width"
              >
                <role-card
                  :role="role"
                  :active-user="activatedUserId"
                  :listLoading.sync="listLoading"
                  @role-edit="handleEdit(role)"
                  @refresh="getAllRole"
                ></role-card>
              </el-col>
            </el-row>
          </div>
        </el-scrollbar>
      </div>
      <div class="user-list">
        <div class="py-2 flex justify-normal">
          <!-- <i
            class="el-icon-d-arrow-left cursor-pointer hover:text-blue-400 text-2xl"
            style="padding: 8px 0 8px 8px"
            @click="showUserView = !showUserView"
          ></i> -->
          <el-button
            text
            class="w-8 mx-2"
            style="font-size: 24px"
            @click="showUserView = !showUserView"
          >
            <svg-icon icon-class="DArrowLeft" />
          </el-button>
          <el-form class="flex" inline @submit.prevent.native>
            <el-form-item>
              <el-input
                maxlength="64"
                v-model="userCondition"
                @blur="() => (userCondition = userCondition.trim())"
                :placeholder="$t('user.search')"
                clearable
                @keyup.enter.native="getAllUser()"
                @clear="getAllUser()"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" class="w-8" @click="getAllUser()">
                <svg-icon icon-class="search" />
              </el-button>
            </el-form-item>
            <el-form-item
              ><el-button
                v-permission="{
                  permission: '12688010.USER_MANAGE',
                }"
                type="primary"
                class="w-8"
                @click="handleUserAdd"
              >
                <svg-icon icon-class="plus" /> </el-button
            ></el-form-item>
          </el-form>
        </div>
        <div style="border-top: 1px solid #f0f2f5">
          <el-scrollbar
            style="height: calc(100vh - 120px)"
            wrap-style="overflow-x:hidden;"
          >
            <el-empty
              v-if="userList.length === 0"
              :description="$t('common.empty_tip')"
            />
            <div v-if="userList.length > 0" class="draggable-container">
              <div
                v-for="user in userList"
                :key="user.userId"
                :data-id="user.userId"
                class="user-list__item cursor-pointer"
                :class="[
                  activatedUserId === user.userId ? 'user-list__item_active' : '',
                  user.username === loginUserName || user.managerFlag === 1
                    ? ''
                    : 'isDraggable',
                ]"
                @click="clickUser(user.userId)"
              >
                <div style="display: flex; min-width: 0; align-items: center">
                  <div style="flex: none" @click.stop>
                    <el-popover
                      placement="right"
                      width="350"
                      trigger="hover"
                      open-delay="300"
                    >
                      <div style="padding: 2px">
                        <div style="display: flex">
                          <img
                            style="height: 56px; width: 56px; margin-right: 12px"
                            :src="getLogo(user.logoUrl)"
                          />
                          <div style="font-size: 22px; font-weight: 700; color: #1a1a1a">
                            {{ user.name }}
                          </div>
                        </div>
                        <div style="padding-top: 8px; font-size: 14px; color: #aaaaaa">
                          <span style="color: #3c3c3c"> {{ $t("common.email") }}: </span>
                          {{ user.email }}
                        </div>
                        <div style="font-size: 14px; color: #aaaaaa">
                          <span style="color: #3c3c3c">
                            {{ $t("user.last_login_time") }}:
                          </span>
                          {{ dateTimeFilter(user.lastLoginTime) }}
                        </div>
                      </div>
                      <template #reference>
                        <div>
                          <div class="user-avatar" style="position: relative">
                            <img
                              :class="[user.status === 0 ? 'user-lock' : '']"
                              style="height: 32px; width: 32px; margin-right: 12px"
                              :src="getLogo(user.logoUrl)"
                            />
                            <svg-icon
                            icon-class="Lock"
                            v-if="user.status === 0"
                            style="
                              position: absolute;
                              top: 8px;
                              left: 8px;
                              font-size: 16px;
                              font-weight: 700;
                            "
                          ></svg-icon>
                          </div>
                        </div>
                      </template>
                    </el-popover>
                  </div>
                  <div style="min-width: 0">
                    <div
                      style="
                        font-size: 14px;
                        color: #1a1a1a;
                        line-height: 20px;
                        overflow: hidden;
                        text-overflow: ellipsis;
                        white-space: nowrap;
                      "
                    >
                      {{ user.name }}
                    </div>
                    <div
                      style="
                        font-size: 12px;
                        color: #aaaaaa;
                        line-height: 14px;
                        overflow: hidden;
                        text-overflow: ellipsis;
                        white-space: nowrap;
                      "
                    >
                      {{ user.email }}
                    </div>
                  </div>
                </div>
                <div class="flex">
                  <div class="user-btn cursor-pointer" @click.stop="handleMenu(user)">
                    <svg-icon icon-class="outlined-safety" style="font-size: 22px" />
                  </div>

                  <div
                    v-permission="{ permission: '12688010.USER_MANAGE' }"
                    v-if="!(user.username === loginUserName || user.managerFlag === 1)"
                    class="user-btn draggable-handle cursor-move"
                  >
                  <svg-icon icon-class="outlined-drag" style="font-size: 22px" />

                  </div>
                </div>
              </div>
            </div>
          </el-scrollbar>
        </div>
      </div>
    </div>

    <transition name="slide">
      <user
        v-show="showUserView"
        v-model:showUserView="showUserView"
        @updateUserView="showUserView = false"
      ></user>
    </transition>

    <role-add
      :type="operationType"
      :role-id="editRoleId"
      @submit="getAllRole"
      v-model="addRoleVisible"
      :title="editRoleId ? $t('role.edit_role_title') : $t('role.add_role_title')"
    ></role-add>
    <user-add
      ref="userDialog"
      :type="operationType"
      :user-id="editUserId"
      :showAddRole="false"
      @submit="refresh"
      v-model="addUserVisible"
      :title="editUserId ? $t('user.edit_user_title') : $t('user.add_user_title')"
    ></user-add>
    <user-permission
      :user="permissionUser"
      v-model="showPermissionDialog"
      :title="$t('user.permission')"
    ></user-permission>
  </div>
</template>

<script>
import { getAllRole } from "@/api/role";
import { addUser, editUser, getUser, getAllUser } from "@/api/user";
import { timeFilter, dateFilter, dateTimeFilter } from "@/filters";
import RoleAdd from "./role-add";
import RoleCard from "./components/role-card";
import UserPermission from "./components/user-permission";
import { parseTime } from "@/utils";
import { Draggable } from "@shopify/draggable";
import UserAdd from "@/views/system/user/user-add";
import User from "./user";
import PageTitle from "@/components/PageTitle/index.vue";
export default {
  components: {
    RoleAdd,
    RoleCard,
    UserPermission,
    UserAdd,
    User,
    PageTitle,
  },
  computed: {
    getBindRoleList() {
      let roleIdList = [];
      this.roleList.forEach((role) => {
        if (role.userList.find((user) => user.userId === this.activatedUserId)) {
          roleIdList.push(role.roleId);
        }
      });
      return roleIdList;
    },
  },
  data() {
    return {
      showUserView: false,
      editUserId: "",
      loginUser: {},
      loginUserName: "",
      showPermissionDialog: false,
      activatedUserId: -1,
      permissionUser: -1,
      userList: [],
      roleList: [],
      tableData: [],
      listLoading: false,
      selectedData: [],
      paginationShow: true,
      userCondition: "",
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      addRoleVisible: false,
      addUserVisible: false,
      operationType: "",
      editRoleId: "",
      draggable: {},
      dragEvt: {
        roleId: -1,
        userId: -1,
      },
      form: {
        userId: "",
        queryOrg: {},
        createType: 0,
        orgId: null,
        username: "",
        name: "",
        email: null,
        mobile: "",
        countryCode: "",
        status: 1,
        roleList: [],
        roleIds: [],
      },
    };
  },
  mounted() {
    this.loginUser = JSON.parse(
      localStorage.getItem(this.$store.getters.keys.storage.username)
    );
    this.loginUserName = this.loginUser.username;
    this.$watch("roleList", (from, to) => {
      if (from.length !== to.length) {
        this.setSortable();
      }
    });
    this.$watch("userList", (from, to) => {
      if (from.length !== to.length) {
        this.setSortable();
      }
    });
    this.getAllRole();
    this.getAllUser();
  },
  watch: {
    showUserView(n) {
      if (!n) {
        this.getAllRole();
        this.getAllUser();
      }
    },
  },
  methods: {
    statusFilter(status) {
      const statusMap = {
        0: "Invalid",
        1: "Valid",
      };
      return statusMap[status];
    },
    timeFilter,
    dateFilter,
    dateTimeFilter,
    handleMenu(user) {
      this.permissionUser = user;
      this.showPermissionDialog = true;
    },
    clickUser(userId) {
      if (userId === this.activatedUserId) {
        this.activatedUserId = -1;
      } else {
        this.activatedUserId = userId;
      }
    },
    addUser() {
      let role = this.roleList.find((role) => {
        return role.roleId == this.dragEvt.roleId;
      });
      if (
        role.userList.find((user) => {
          return user.userId == this.dragEvt.userId;
        })
      ) {
        this.$message.error(this.$t("user.duplicate_role_tip"));
        return;
      }
      let user = this.userList.find((user) => {
        return user.userId == this.dragEvt.userId;
      });
      let userName = ` <span style="color:#409EFF">${user.name}</span>`;
      let roleName = ` <span style="color:#409EFF">${role.roleName}</span>`;
      this.$confirm(
        this.$t("user.user_add_confirm", { userName, roleName }),
        this.$t("common.tips"),
        {
          confirmButtonText: this.$t("common.confirm"),
          cancelButtonText: this.$t("common.cancel"),
          type: "warning",
          dangerouslyUseHTMLString: true,
        }
      ).then(() => {
        this.getUserInfo();
      });
    },
    getUserInfo() {
      this.listLoading = true;
      getUser(this.dragEvt.userId)
        .then((res) => {
          this.form.userId = this.dragEvt.userId;
          this.form.roleIds = [];
          this.form.username = res.username;
          this.form.orgId = res.orgId;
          this.form.name = res.name;
          this.form.email = res.email;
          this.form.mobile = res.mobile;
          this.form.countryCode = res.countryCode;
          this.form.status = res.status;
          if (res.roleList) {
            res.roleList.forEach((role) => {
              this.form.roleIds.push(role.roleId);
            });
          }
          this.form.roleIds.push(this.dragEvt.roleId);
          console.log(this.form.roleIds);
          /* this.$nextTick(() => {
          this.$refs.organizationTree.initData()
        }) */
          this.saveUser();
        })
        .catch((err) => {
          this.$confirmError(err);
          this.listLoading = false;
        });
    },
    saveUser() {
      if (this.form.roleIds.length > 5) {
        console.log(this.form.roleIds);
        this.$message.error(this.$t("user.max_role_error"));
        this.listLoading = false;
        return;
      }
      // role info
      this.form.roleList = [];
      this.form.roleIds.forEach((roleId) => {
        this.form.roleList.push({ roleId: roleId });
      });
      this.form.platCode = ["PASS"];
      if (this.form.userId) {
        editUser(this.form)
          .then(() => {
            this.$message({
              message: this.$t("common.success"),
              type: "success",
            });
            this.getAllRole();
          })
          .catch((e) => {
            this.listLoading = false;
            this.$confirmError(e);
          });
      }
    },
    setSortable() {
      this.$nextTick(() => {
        const containers = document.querySelectorAll(".draggable-container");
        console.log(containers);
        if (Object.keys(this.draggable).length) {
          this.draggable.destroy();
        }
        if (containers.length === 0) {
          return false;
        }
        this.draggable = new Draggable(containers, {
          draggable: ".isDraggable",
          handle: ".draggable-handle",
          mirror: {
            constrainDimensions: true,
          },
          delay: 160,
        });
        this.draggable.on("drag:stop", (evt) => {
          if (this.dragEvt.roleId === -1) {
            return;
          }
          this.addUser();
        });
        this.draggable.on("drag:over:container", (evt) => {
          this.dragEvt.roleId = evt.overContainer.dataset.id
            ? evt.overContainer.dataset.id
            : -1;
          this.dragEvt.userId = evt.originalSource.dataset.id
            ? evt.originalSource.dataset.id
            : -1;
        });
        this.draggable.on("drag:out:container", (evt) => {
          this.dragEvt.roleId = -1;
          this.dragEvt.userId = -1;
        });
      });
    },
    getLogo(logo) {
      if (logo) {
        let avatars = this.$store.getters.avatars.find((v) => v.name == logo);
        if (avatars) {
          return avatars.src;
        }
      }
      return this.$store.getters.avatars[0].src;
    },
    refresh() {
      this.getAllUser();
      this.getAllRole();
    },
    getAllUser() {
      this.userCondition = this.userCondition.trim();
      getAllUser({
        condition: this.userCondition,
        platCode: 'PASS'
      })
        .then((res) => {
          this.userList = res;
        })
        .catch(this.$confirmError);
    },
    getAllRole() {
      this.listLoading = true;
      getAllRole({
        platCode: "PASS",
        includeUserFlag: 1,
      })
        .then((res) => {
          this.roleList = res;
          this.listLoading = false;
        })
        .catch((err) => {
          this.$confirmError(err);
          this.listLoading = false;
        });
    },

    handleEdit(row) {
      this.editRoleId = row.roleId;
      this.operationType = "update";
      this.addRoleVisible = true;
    },
    handleAdd() {
      this.editRoleId = "";
      this.operationType = "add";
      this.addRoleVisible = true;
    },
    handleUserAdd() {
      this.operationType = "add";
      this.addUserVisible = true;
      this.$refs.userDialog.init("");
    },

    formatDate(row, column, cellValue, index) {
      return parseTime(cellValue, "{y}-{m}-{d}");
    },
  },
};
</script>

<style lang="scss" scoped>
@import "@/styles/variables.scss";

.auto-width {
  width: 100%;
}

@media screen and (min-width: 1280px) {
  .auto-width {
    width: 50%;
  }
}

@media screen and (min-width: 1600px) {
  .auto-width {
    width: 33%;
  }
}

@media screen and (min-width: 1900px) {
  .auto-width {
    width: 25%;
  }
}

.user-lock {
  filter: grayscale(0.9) opacity(0.3);
}
.draggable-mirror {
  border-radius: 4px;
  box-shadow: $boxShadow;
}

.user-list {
  background: #fff;
  box-shadow: $boxShadow;
  width: 340px;
  flex: none;
  height: calc(100vh - 60px);
  position: relative;
  bottom: 16px;
  left: 16px;
  .user-list__item {
    padding: 10px 20px;
    border-bottom: 1px solid #e9edf3;
    display: flex;
    align-items: center;
    justify-content: space-between;
    background-color: #fff;

    img {
      margin-right: 5px;
      border-radius: 50%;
      &:hover {
        box-shadow: rgba(17, 17, 26, 0.5) 0px 4px 4px;
      }
    }
  }

  .user-list__item:firs t-child {
    border-top: 1px solid #e9edf3;
  }

  .user-list__item_active {
    border-left: solid 3px var(--el-color-primary);
  }

  .user-list__item.isDraggable:hover {
    background-color: #f5f7fa;
  }
  .background-red {
    background-color: #faecd8;
  }
  .background-grey {
    background-color: #e9e9eb;
    cursor: not-allowed;
  }
}

.user-btn {
  font-size: 0px;
  margin-left: 4px;
  color: #aaaaaa;

  &:hover {
    color: #409eff;
  }
}

.isDraggable {
  cursor: pointer;
}

.terminal-list {
  .el-table .cell {
    /* height: 30px !important; */
  }
}

.query-button {
  margin-left: 30px;
}

.svg-container {
  cursor: pointer;
  margin-top: 6px;
  margin-left: 20px;
  font-size: 24px;
  display: inline-block;
}

.pagination-wrapper {
  text-align: right;
}
.slide-enter-active,
.slide-leave-active {
  transition: all 0.5s ease-in-out;
}

.slide-enter,
.slide-leave-to {
  transform: translateX(100%);
}

.clearfix::before,
.clearfix::after {
  content: "";
  display: block;
  clear: both;
  overflow: hidden;
}
</style>
